import React, { useState } from "react";
import { View, ViewProps } from "@tarojs/components";
import { DeleteIcon, SettingIcon } from "../Icons";
import "./index.less";

interface SwipeableCardProps extends ViewProps {
  onDelete?: () => void;
  onEdit?: () => void;
  children: React.ReactNode;
  className?: string;
  threshold?: number;
  childCls?: string;
}

const SwipeableCard: React.FC<SwipeableCardProps> = ({
  onDelete,
  onEdit,
  children,
  className = "",
  threshold = -120,
  childCls = "",
  ...others
}) => {
  const [offset, setOffset] = useState(0);
  const [startX, setStartX] = useState(0);
  const [isDragging, setIsDragging] = useState(false);

  const deleteThreshold = -100;
  const editThreshold = 100;

  const handleTouchStart = (e) => {
    setStartX(e.touches[0].clientX);
    setIsDragging(true);
  };

  const handleTouchMove = (e) => {
    if (!isDragging) return;
    const currentX = e.touches[0].clientX;
    const diff = currentX - startX;

    if ((onDelete && diff < 0) || (onEdit && diff > 0)) {
      const newOffset = Math.max(-120, Math.min(120, diff));
      setOffset(newOffset);
    }
  };

  const handleTouchEnd = () => {
    if (offset < -Math.abs(deleteThreshold)) {
      onDelete?.();
    } else if (offset > Math.abs(editThreshold)) {
      onEdit?.();
    }

    resetPosition();
    setIsDragging(false);
  };

  const resetPosition = () => {
    setOffset(0);
    setIsDragging(false);
  };

  const deleteOpacity = Math.min(1, Math.abs(offset) / 100);
  // 计算编辑按钮透明度
  const editOpacity = Math.min(1, Math.abs(Math.max(0, offset)) / 100);

  return (
    <View className={`swipeable-card ${className}`} {...others}>
      <View
        className="swipeable-card-action swipeable-card-action-del"
        style={{
          opacity: deleteOpacity,
        }}
      >
        <DeleteIcon type="white" size={1.6} />
      </View>
      <View
        className="swipeable-card-action swipeable-card-action-edit"
        style={{
          opacity: editOpacity,
        }}
      >
        <SettingIcon type="white" size={1.6} />
      </View>

      <View
        className={`swipeable-card-content ${childCls}`}
        style={{
          transform: `translateX(${offset}px)`,
          transition: isDragging
            ? "none"
            : "transform 0.3s ease-out, opacity 0.3s ease-out",
        }}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        {children}
      </View>
    </View>
  );
};

export default SwipeableCard;
